<?php
/**
 * Created by PhpStorm.
 * Author: DaXiong
 * Date: 2018/10/26
 * Time: 11:44
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Cates;
use App\Models\Comments;
use App\Models\Users;
use App\Models\Videos;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class VideoController extends Controller
{

    /**
     * 视频管理_列表
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function index()
    {
        try {
            $params = [
                'title' => (string)request('name', ''),
                'chanel_id' => (int)request('chanel_id', 0),
                'cate_id' => (int)request('cate_id', 0),
                'sort' => (int)request('sort', 0),
                'option' => (int)request('option', 0),
                'good' => (int)request('good', 0),
                'wheel' => (int)request('wheel', 0),
                'admins' => (int)request('admins', 0),
                'start' => request('start', ''),
                'end' => request('end', ''),
            ];
            switch ($params['sort']) {
                case 1:
                    $sort = 'view';
                    break;
                case 2:
                    $sort = 'share_count';
                    break;
                default:
                    $sort = 'id';
                    break;
            }
            $userid = auth()->guard('api')->id();
            $lists = Videos::where(function ($query) use ($params, $userid) {
                if ($params['title']) {
                    $query->where('title', 'like', '%' . $params['title'] . '%');
                }
                if ($params['chanel_id']) {
                    $query->where('chanel_id', $params['chanel_id']);
                }
                if ($params['cate_id']) {
                    $query->where('cate_id', $params['cate_id']);
                }
                if ($params['option']) {
                    if ($params['option'] === Videos::OPTION_1) {
                        $query->where('option', Videos::OPTION_1);
                    } else {
                        $query->where('option', Videos::OPTION_0);
                    }
                }
                if ($params['good']) {
                    if ($params['good'] === Videos::GOOD_1) {
                        $query->where('good', Videos::GOOD_1);
                    } else {
                        $query->where('good', Videos::GOOD_0);
                    }
                }
                if ($params['wheel']) {
                    if ($params['wheel'] === Videos::WHEEL_1) {
                        $query->where('wheel', Videos::WHEEL_1);
                    } else {
                        $query->where('wheel', Videos::WHEEL_0);
                    }
                }
                if ($params['start']){
                    $query->whereDate('created_at','>=',$params['start']);
                }
                if ($params['end']){
                    $query->whereDate('created_at','<=',$params['end']);
                }
                if ($params['admins']>0) {
                    $query->where('userid', $params['admins']);
                }
            })
                ->with(['cate' => function ($query) {
                    $query->select('id', 'name')->get();
                }])
                ->with(['user' => function ($query) {
                    $query->select('id', 'username')->get();
                }])
                ->withCount('comment')
                ->orderBy($sort, 'DESC')
                ->paginate(10);
            $this->stateToText($lists, [
                'status' => Videos::STATUS_TEXT,
                'option' => Videos::OPTION_TEXT,
                'good' => Videos::GOOD_TEXT,
                'wheel' => Videos::WHEEL_TEXT
            ]);
            $counts = Videos::where(function ($query) use ($params, $userid) {
                if ($params['title']) {
                    $query->where('title', 'like', '%' . $params['title'] . '%');
                }
                if ($params['chanel_id']) {
                    $query->where('chanel_id', $params['chanel_id']);
                }
                if ($params['cate_id']) {
                    $query->where('cate_id', $params['cate_id']);
                }
                if ($params['option']) {
                    if ($params['option'] === Videos::OPTION_1) {
                        $query->where('option', Videos::OPTION_1);
                    } else {
                        $query->where('option', Videos::OPTION_0);
                    }
                }
                if ($params['good']) {
                    if ($params['good'] === Videos::GOOD_1) {
                        $query->where('good', Videos::GOOD_1);
                    } else {
                        $query->where('good', Videos::GOOD_0);
                    }
                }
                if ($params['wheel']) {
                    if ($params['wheel'] === Videos::WHEEL_1) {
                        $query->where('wheel', Videos::WHEEL_1);
                    } else {
                        $query->where('wheel', Videos::WHEEL_0);
                    }
                }
                if ($params['admins']) {
                    $query->where('userid', $params['admins']);
                }
                if ($params['start']){
                    $query->whereDate('created_at','>=',$params['start']);
                }
                if ($params['end']){
                    $query->whereDate('created_at','<=',$params['end']);
                }
            })->select(\DB::raw("sum(view) as view, sum(share) as share, sum(share_count) as share_all"))->get()->toArray();
            $msg['count'] = $counts[0];
            $msg['admins'] = Users::where('is_admin', Users::ADMIN_1)->select('id', 'username')->get();
            return $this->returnJson(0, $msg, $lists);
        } catch (\Exception $e) {
            Log::info("video调试错误:");
            Log::info($e->getMessage());
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }

    public function update()
    {
        $data = request()->all();
        $video = $this->getVideo($data['link']);
        if (!$video) {
            return $this->returnJson(1, '视频链接有误');
        }
        $data['time'] = $video['time'];
        $data['userid'] = auth()->guard('api')->id();
        if ($data['id']) {
            //编辑
            $info = Videos::find($data['id']);
            if (!$info) {
                return $this->returnJson(1, '数据不存在');
            }
            if(isset($data['userid'])){
                unset($data['userid']);
            }
            $info->update($data);
            return $this->returnJson(0, '编辑视频信息成功');
        } else {
            //新增
            //抓取腾讯视频
            $result = preg_match_all('/\/([0-9a-zA-Z]+).html/', $data['link'], $matchs);
            if ($result) {
                $matchs = array_flatten($matchs);
            }
            $vid = $matchs[1] ?? '';
            //判断数据是否存在，去重（标题&链接ID）
            $is_video = Videos::where('title',$data['title'])->orWhere('link','like','%'.$vid.'%')->first();
            if($is_video){
                return $this->returnJson(1, '该视频已经存在！');
            }
             //获取分类统计数
            $catesTotal = Cates::count();
            $catesRandKey = rand(0,$catesTotal-1);
            $cateList = Cates::skip($catesRandKey)->take(1)->get();
            $data['cate_id'] = $cateList[0]['id'];

            $data['status'] = Videos::STATUS_1;
            $data['view'] = 0;
            $data['zan_count'] = rand(500, 1000);
            $data['sort'] = time() + rand(1, 40000);//时间+随机数，用于每天数据更新的顺序，防止重复出现同一个类的数据
            $data['rand_cate'] = rand(1, 30);//随机分类，用于详情页随机展示列表
            Videos::create($data);
            return $this->returnJson(0, '新增视频信息成功');
        }
    }

    protected function getComments($vid, $id)
    {
        if (empty($vid)) return false;
        $url = 'https://ncgi.video.qq.com/fcgi-bin/video_comment_id?otype=json&callback=jQuery19107498598488382213_1542096743408&op=3&vid=' . $vid;
        $res = $this->httpsRequest($url);
        $res = str_replace('jQuery19107498598488382213_1542096743408(', '', $res);
        $res = rtrim($res, ")");
        $res = json_decode($res, true);
        $comment_id = $res['comment_id'];
        if ($comment_id) {
            $pageNum = 30;//只取视频前30条评论，一页最多只能取30条数据
            $cursor = 0;//只取第一页数据
            $link = 'https://video.coral.qq.com/varticle/' . $comment_id . '/comment/v2?callback=_varticle' . $comment_id . 'commentv2&orinum=' . $pageNum . '&oriorder=o&pageflag=1&cursor=' . $cursor . '&scorecursor=0&orirepnum=2&reporder=o&reppageflag=1&source=9&_=1542098264908';
            $result = $this->httpsRequest($link);
            $result = str_replace('\n', '', $result);
            $result = str_replace('_varticle' . $comment_id . 'commentv2(', '', $result);
            $result = rtrim($result, ")");
            $result = json_decode($result, true);
//        $data = ;//评论数据
//        $lastPage = $result['data']['last'];//获取下一页
//        $hasnext = $result['data']['hasnext'];//是否存在下一页
//        dd($result);
//        if($hasnext){
//            return $this->getComments($comment_id,$lastPage,$data);
//        }
//            dump($result['data']['userList']);die;
            $userList = $result['data']['userList'];
            $oriCommList = $result['data']['oriCommList'];


//            foreach ($oriCommList as $key => $c) {
//                $time = Carbon::now()->subHours(rand(1, 24));
//                $uid = $c['userid'];
//                $user = Users::where('openid', $uid)->first();
//                if (!$user) {
//                    //不存在创建新用户
//                    $user = Users::create([
//                        'openid' => $uid,
//                        'avatar' => $userList[$uid]['head'],
//                        'username' => $userList[$uid]['nick'],
//                        'password' => bcrypt($uid),
//                        'register_at' => Carbon::now(),
//                        'login_at' => Carbon::now(),
//                    ]);
//                }
////                $user = Users::where('username','<>','')->where('avatar','<>','')
////                    ->where('is_admin',0)->inRandomOrder()->first();
//                Comments::insert([
//                    'video_id' => $id,
//                    'content' => $c['content'],
//                    'userid' => $user['id'],
//                    'replay_id' => 0,
//                    'praise' => $c['up'],
//                    'created_at' => $time,
//                    'add_at' => $time,
//                ]);
//            };

            return count($oriCommList);

        }
    }


    /**
     * 视频管理_删除
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function destroy()
    {
        try {
            $id = (int)request('id', 0);
            Videos::destroy($id);
            return $this->returnJson(0);
        } catch (\Exception $e) {
            return $this->returnJson(1, '删除失败');
        }
    }

    /**
     * 获取当天视频，用于模板消息推送
     * @return \Illuminate\Http\JsonResponse
     */
    public function todayVideos()
    {
        try {
            $lists = Videos::whereDate('created_at', Carbon::now()->toDateString())
                ->get(['id', 'title']);
            return $this->returnJson(0, '', $lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, '删除失败');
        }

    }

    /**
     * 批量视频删除
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroyAll()
    {

        $lists = request('data', '');
        if ($lists) {
            try {
                Videos::destroy($lists);
                return $this->returnJson(0,'',$lists);
            } catch (\Exception $e) {
                return $this->returnJson(1, '删除失败');
            }
        }
        return $this->returnJson(1, '删除失败');
    }

}
